package com.atguigu.flink.chapter09;

import com.atguigu.flink.bean.WaterSensor;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.cep.CEP;
import org.apache.flink.cep.PatternSelectFunction;
import org.apache.flink.cep.PatternStream;
import org.apache.flink.cep.PatternTimeoutFunction;
import org.apache.flink.cep.pattern.Pattern;
import org.apache.flink.cep.pattern.conditions.SimpleCondition;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.util.OutputTag;

import java.io.OutputStream;
import java.time.Duration;
import java.util.List;
import java.util.Map;


public class Flink10_CEP_WithIn {
       public static void main(String[] args) {
               Configuration configuration = new Configuration();
               //web  UI端口
               configuration.setInteger("rest.prot",10000);
               StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
               env.setParallelism(1);

           SingleOutputStreamOperator<WaterSensor> waterStream = env.readTextFile("input/sensor12.txt")
                   .map(new MapFunction<String, WaterSensor>() {
                       @Override
                       public WaterSensor map(String value) throws Exception {
                           String[] data = value.split(",");
                           return new WaterSensor(
                                   data[0],
                                   Long.valueOf(data[1]),
                                   Integer.valueOf(data[2])
                           );
                       }
                   }).assignTimestampsAndWatermarks(
                        WatermarkStrategy
                            .<WaterSensor>forBoundedOutOfOrderness(Duration.ofSeconds(5))
                            .withTimestampAssigner(((element, recordTimestamp) -> element.getTs()))
                   );


           //2.定义模式
           Pattern<WaterSensor, WaterSensor> pattern = Pattern
                   //模式名字只能是字符，不能包含符号，且独一无二
                   .<WaterSensor>begin("start")
                   .where(new SimpleCondition<WaterSensor>() {
                       @Override
                       public boolean filter(WaterSensor value) throws Exception {
                           return "sensor_1".equals(value.getId());
                       }
                   })

                   .next("end")
                   .where(new SimpleCondition<WaterSensor>() {
                       @Override
                       public boolean filter(WaterSensor value) throws Exception {
                           return "sensor_2".equals(value.getId());
                       }
                   })
                   //对于sensor_1和sensor_2 在2秒之内才能匹配上
                   .within(Time.seconds(2));





           //3.把模式作用在流上，得到一个模式流
           PatternStream<WaterSensor> ps = CEP.pattern(waterStream, pattern);


           //4.从模式流中获取匹配到的数据
           SingleOutputStreamOperator<String> normal = ps.select(new OutputTag<String>("late") {},
                   new PatternTimeoutFunction<WaterSensor, String>() {
                       @Override
                       public String timeout(Map<String, List<WaterSensor>> map, long timeoutTimestamp) throws Exception {
                           // 返回值，自动放入侧输出流
                           return map.toString();
                       }
                   },
                   new PatternSelectFunction<WaterSensor, String>() {
                       @Override
                       public String select(Map<String, List<WaterSensor>> map) throws Exception {
                           return map.toString();
                       }
                   }
           );
           normal.print("正常"); //匹配成功
           normal.getSideOutput(new OutputTag<String>("late") {}).print("超时匹配");
           // 不能输出匹配不上的数据！！！


           try {
                   env.execute();
               } catch (Exception e) {
                   e.printStackTrace();
               }


           }
}
